package com.dd.keel.core.common.utils;


import java.io.InputStream;
import java.io.Reader;
import java.io.IOException;
import java.io.CharArrayWriter;
import java.io.BufferedReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Some util for reading stream 
 * @author Kevin.XU
 *
 */
public class IOUtil {
	
	final static private Logger LOGGER = LoggerFactory.getLogger(IOUtil.class);
	
	/**
	 * 从流读数据
	 * @param input
	 * @param pakb
	 * @param off
	 * @param count
	 * @param buffer_size
	 * @throws EOFException
	 * @throws IOException
	 */
	public static void readByteFromStream(InputStream input,byte[] pakb,int off,int count,int buffer_size) throws Exception,IOException
	{
		int curr_off = off;
		if( count > buffer_size )
		{
			int needDataLen = count;
			while( needDataLen > 0 )
			{
				int readedlen = 0;
				if( needDataLen > buffer_size )
				{
					readedlen = input.read(pakb, curr_off, buffer_size);
				}else{
					readedlen = input.read(pakb, curr_off, needDataLen);
				}
				if(readedlen==-1) break;
				needDataLen -= readedlen;
				curr_off += readedlen;
				LOGGER.debug("read {}, need read {}", readedlen , needDataLen);
			}
		}
		else
		{
			int readedlen = input.read(pakb, off, count);
			if(readedlen==-1) throw new Exception("EOF!");
		}
	}
	
	public static byte[] readByteFromStream(InputStream input,int total_size,int buffer_size) throws Exception
	{
		byte[] pakb = new byte[total_size];
		readByteFromStream(input,pakb,0,total_size,buffer_size);
		return pakb;
	}
	
	public static byte[] readByteFromFileStream(InputStream input,int total_size,int buffer_size) throws Exception
	{
		try{
			if(input.available()==0) return null;
		}catch(Exception ex){
			LOGGER.error( ex.getMessage(), ex );
		}
		return readByteFromStream(input,total_size,buffer_size);
	}
	
	public static char[] readCharFromReader(Reader reader)
	{
		char[] temp = null;
		CharArrayWriter caw = new CharArrayWriter();
		BufferedReader br = new BufferedReader(reader);
		try{
			char[] buffer = new char[1024];
			int count= 0;
			while( (count=br.read(buffer,0,1024))>0 )
			{
				caw.write(buffer, 0, count);
			}
			temp = caw.toCharArray();
			br.close();
			caw.close();
		}catch(Exception ex){
			LOGGER.error( ex.getMessage(), ex );
		}
		return temp;
	}
	
}